package com.zhaotianhao.serviceuser.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhaotianhao.serviceuser.common.JsonResult;
import com.zhaotianhao.serviceuser.common.WebUtils;
import com.zhaotianhao.serviceuser.dto.UserLoginDTO;
import com.zhaotianhao.serviceuser.entity.Captcha;
import com.zhaotianhao.serviceuser.entity.User;
import com.zhaotianhao.serviceuser.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Z-7
 * @since 2022-04-25
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Value("${jwt.key}")
    private String jwtKey;
    private final String captchaPath = "D:/imgs/captcha/";
    private final String captchaHost = "http://localhost:8200/";
    private final String key = "4565613d4b0e434cb496d4eb87feb45f";

    @Autowired
    private IUserService iUserService;
    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping("getCaptcha")
    public Captcha getCaptcha() {
        log.info("开始生成验证码");
        // 生成验证码
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 4, 4);
        // 设置四则运算
        //captcha.setGenerator(new MathGenerator());
        String uuid = UUID.randomUUID().toString();
        // 文件名称
        String captchaName = uuid + ".png";
        // 缓存名称
        String cacheName = "captcha" + uuid;
        // 绝对路径
        String absolutePath = captchaPath + captchaName;
        // 生成文件
        captcha.write(absolutePath);
        // 存入redis 限时1min
        redisTemplate.opsForValue().set(cacheName, captcha.getCode(), 1, TimeUnit.MINUTES);
        // 拼接路径
        String url = captchaHost + captchaName;
        log.info("生成验证码结束");
        return new Captcha().setCaptchaUrl(url).setCaptchaName(captchaName).setCacheName(cacheName);
    }

    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO user) {
        Object obj = redisTemplate.opsForValue().get(user.getCache());
        // 验证码的判断
        if (!obj.toString().equals(user.getCaptcha())) {
            log.error("验证码错误");
            return JsonResult.faild(HttpStatus.PRECONDITION_FAILED.value(), "验证码输入错误");
        }
        // 删除redis中的数据
        redisTemplate.delete(user.getPhone());
        // 非空校验
        if (StringUtils.isEmpty(user.getPhone()) || StringUtils.isEmpty(user.getPassword())) {
            log.error("手机号或密码为空");
            return JsonResult.faild("请填写完成后登录");
        }
        String userKey = user.getPhone();
        if (redisTemplate.hasKey(userKey)) {
            if ((Integer) redisTemplate.opsForValue().get(userKey) == 3) {
                log.error("错误次数达到上限");
                return JsonResult.faild("账户已锁定，联系后台管理");
            }
        }

        // 校验用户合法性
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", user.getPhone());
        User login = iUserService.getOne(queryWrapper);
        if (login == null) {
            log.error("用户不存在");
            return JsonResult.faild("用户名称或密码错误");
        }
        // 密码加盐加密
        String salt = login.getSalt();
        String password = SecureUtil.md5(user.getPassword() + key + salt);
        System.out.println("pass:" + password);
        // 判断密码
        if (!password.equals(login.getPassword())) {
            log.error("密码");
            redisTemplate.opsForValue().increment(userKey, 1);
            return JsonResult.faild("用户名称或密码错误");
        }
        redisTemplate.delete(userKey);
        // 存在
        String token = JWT.create().setKey(jwtKey.getBytes())
                .setPayload("userId", login.getId())
                .setPayload("username", login.getUsername())
                .setExpiresAt(DateUtil.offsetDay(DateUtil.date(), 1))
                .sign();
        return JsonResult.successd(token);
    }

    @GetMapping("getLoginUser")
    public JsonResult getLoginUser() {
        // 获取请求中的token  判断用户是否合法
        String token = WebUtils.getRequest().getHeader("token");
        if (StringUtils.isEmpty(token) || "null".equals(token)) {
            return JsonResult.faild(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(),"用户不存在");
        }
        JWT jwt = JWT.of(token).setKey(jwtKey.getBytes());
        if (!jwt.validate(0)) {
            log.error("验证失败");
            return JsonResult.faild(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(),"用户失效哦");
        }
        return JsonResult.successd(token);
    }
}
